﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace DicomLibrary.Rendering
{
    public class DBitmap
    {
        public int WindowWidth { get; set; }
        public int WindowLevel { get; set; }

        private int imageWidth { get; set; }
        private int imageHeight { get; set; }

        private bool isPixelData16 { get; set; }
        private byte[] pixelData8 { get; set; }
        private ushort[] pixelData16 {get;set;}

        private Bitmap _bitmap;
        public Bitmap Bitmap
        {
            get
            {
                ReloadBitmap();
                return this._bitmap;
            }
        }
        
        private void ReloadBitmap()
        {
            Bitmap bmp = new Bitmap(imageWidth, imageHeight);
            BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

            IntPtr ptr = bitmapData.Scan0;
            int bytes = Math.Abs(bitmapData.Stride) * bmp.Height;
            byte[] rgbValues = new byte[bytes];
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

            int minValue = WindowLevel - WindowWidth / 2;
            int maxValue = WindowLevel + WindowWidth / 2;
          
            for (int counter = 0; counter < rgbValues.Length; counter++)
            {
                byte oColor;
                if (pixelData8[counter/3] < minValue)
                    oColor = 0;
                else if (pixelData8[counter / 3 ] > maxValue)
                    oColor = 255;
                else
                    oColor = (byte)(((pixelData8[counter / 3] - (WindowLevel - (WindowWidth / 2))) * 255) / WindowWidth);

                rgbValues[counter] = oColor;
            }
            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
            bmp.UnlockBits(bitmapData);

            this._bitmap = bmp;
        }

        public DBitmap(DFile dicomFile)
        {
            pixelData8 = (byte[])dicomFile.DataElements.Single(pd => pd.Tag.GroupNumber == 0x7FE0 && pd.Tag.ElementNumber == 0x0010).Value;
            imageWidth = (ushort)dicomFile.DataElements.Single(pd => pd.Tag.GroupNumber == 0x0028 && pd.Tag.ElementNumber == 0x0010).Value;
            imageHeight = (ushort)dicomFile.DataElements.Single(pd => pd.Tag.GroupNumber == 0x0028 && pd.Tag.ElementNumber == 0x0011).Value;

            WindowWidth = 250;
            WindowLevel = WindowWidth / 2;
        }
    }
}
